#!/usr/bin/env ruby
print "Content-type: text/plain\n\n"
ENV['OSMLIBX_XML_PARSER']='usr/lib/ruby/1.8/xml/libxml.rb'



require '/usr/local/lib/site_ruby/gratr.rb'
require '/usr/local/lib/site_ruby/gratr/adjacency_graph.rb'
require '/usr/local/lib/site_ruby/gratr/dot.rb'

require 'yaml'
require '/usr/lib/ruby/1.8/pp.rb'
require '/var/lib/gems/1.8/gems/osmlib-base-0.1.4/lib/OSM/Database.rb'
require '/var/lib/gems/1.8/gems/osmlib-export-0.1.4/lib/OSM/Export.rb'
require '/var/lib/gems/1.8/gems/osmlib-export-0.1.4/lib/OSM/Export/KML.rb'
require '/var/lib/gems/1.8/gems/osmlib-base-0.1.4/lib/OSM/objects.rb'
#require '/var/lib/gems/1.8/gems/osmlib-base-0.1.4/lib/OSM/StreamParser.rb'
require '/var/lib/gems/1.8/gems/osmlib-base-0.1.4/lib/OSM/StreamParser/Libxml.rb'
require '/var/lib/gems/1.8/gems/osmlib-base-0.1.4/lib/OSM/API.rb'


thegraph = GRATR::UndirectedGraph.new

db = OSM::Database.new

parser = OSM::StreamParser.new(:filename => 'smallmap2.osm', :db => db)

parser.parse

db.ways.values.each do |way|

    childindex = 0
    firsttime = true
    way.node_objects.each do |node|
        data = node.id
        if firsttime
            thegraph.add_vertex!(data)
            childindex = 1
            firsttime = false
            next
        end
        #idx = way.node_objects.index(node)
        #childindex = idx +1
        #puts 'the child index'
        #puts way.name if way.name
        #puts way.node_objects[childindex].id
        #puts way.node_objects[childindex]
        #puts 'the node id'
        #puts node.id
        #puts "======================="
        
        childindex -= 1
        if !thegraph.vertex?(data)  
            #puts data 
        end
        thegraph.add_vertex!(data) if !thegraph.vertex?(data)
        thegraph.add_edge!(data, way.node_objects[childindex].id)
    end
end
#puts thegraph.inspect
thegraph.vertices.each do |vert|
    #puts vert
end
thegraph.edges.each do |edge|
    puts "++++++"
    puts edge
end 
puts thegraph.vertex?(65310828)

kmling = OSM::Export::KML.new
kmling 
#def setup :KML do
#    name 'osmdatakml'
#    description 'small kml sample'
#
#    ways do
#        :ways << {:id => "w#{id}", :name => name }
#    end
#end

#thegraph.write_to_graphic_file('jpg','visualize')
